!function () {
	layui.config({base: '/layui/lay/modules/'}).use(['layer', 'form', 'table'], function () {
		var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;

        var Menu = {
            tableId: "menuTable",    //表格id
            condition: {            //查询条件
                menuCode: "",
                menuName: "",
                level: ""
            }
        };

        /**
         * 初始化表格的列
         */
        Menu.initColumn = function () {
            return [[
                /*{type: 'checkbox'},*/
                {field: 'menuId', hide: true, sort: true, title: 'id'},
                {field: 'menuCode', sort: true, title: '菜单编号'},
                {field: 'menuName', sort: true, title: '菜单名称'},
                {field: 'parentCode', sort: true, title: '菜单父编号', width: 120},
                {field: 'menuLink', sort: true, title: '请求地址', width: 200},
                {field: 'menuNum', sort: true, title: '排序', width: 100},
                {field: 'menuTop', sort: true, title: '层级', width: 100},
                {field: 'menuType', sort: true, title: '类型', width: 100,templet: function (row) {
                        return row.menuType == 1 ? '菜单' : '动作';
                    }},
                {field: 'status', sort: true, title: '状态', width: 100,templet: function (row) {
                        return row.status == 1 ? '启用' : '禁用';
                    }},
                {align: 'center', toolbar: '#barDemo', width: 180,title: '操作', minWidth: 200}
            ]];
        };

        /**
         * 点击菜单树时
         */
        Menu.onClickMenu = function (event, treeId, treeNode) {
            Menu.condition.menuCode = treeNode.menuCode;
            Menu.search();
        };

        /**
         * 点击查询按钮
         */
        Menu.search = function () {
            var queryData = {};
            queryData['menuCode'] = Menu.condition.menuCode;
            queryData['menuName'] = $("#menuName").val();
            queryData['menuTop'] = $("#menuTop").val();
            table.reload(Menu.tableId, {where: queryData,page: {curr: 1}});
        };

        /**
         * 弹出添加菜单对话框
         */
        Menu.openAddMenu = function () {
            form.render('radio').val('menuForm', {menuId: '', menuName: '', menuLink: '', menuStyle: ''});
            layer.open({
                type: 1, maxmin: true, title: '添加菜单', shade: 0.4, shadeClose: false,
                area: ['452px', '600px'], content: $('#menuForm').show(), btn: ['保存', '取消'],
                yes: function () {
                    $('#saveMenu').click();
                }, btn2: function () {
                    layer.closeAll();
                }, end: function () {
                    $('#menuForm').hide();
                }
            });
        };

        /**
         * 点击编辑菜单按钮时
         *
         * @param data 点击按钮时候的行数据
         */
        Menu.onEditMenu = function (menuId) {
            $.ajax({
                async: false,
                url: '/menu/findMenuByMenuId?menuId=' + menuId,
                success: function (result) {
                    if (result && result.code == 200) {
                        var data = result.data;
                        //截取菜单编号
                        var menuCode = data.menuCode.split(data.parentCode+'_')[1];
                        $('input[name=menuType]').eq(data.menuType - 1).click();//redis初始化
                        $('input[name=status]').eq(data.status - 1).click();//redis初始化
                        form.render('radio').val('menuForm', {
                            menuId: data.menuId,
                            menuCode: menuCode,
                            menuName: data.menuName,
                            menuLink: data.menuLink,
                            parentCode: data.parentCode,
                            menuType: data.menuType,
                            status: data.status == 1
                        });
                        //选中菜单
                        menuTree.checkAllNodes(false);
                        menuTree.checkNode(menuTree.getNodeByParam('menuCode', data.parentCode), true, true);
                        layer.open({
                            type: 1, maxmin: true, title: '编辑菜单', area: ['452px', '550px'],
                            content: $('#menuForm').show(), btn: ['保存', '取消'], yes: function () {
                                $('#saveMenu').click();
                            }, btn2: function () {
                                layer.closeAll();
                            }, end: function () {
                                $('#menuForm').hide();
                            }
                        });
                    } else
                        layer.alert(result.msg || '请求失败了！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
        };

        /**
         * 点击删除菜单按钮
         *
         * @param data 点击按钮时候的行数据
         */
        Menu.onDeleteMenu = function (menuId) {
            $.ajax({
                async: false,
                type: 'post',
                url: '/menu/delMenu?menuId=' + menuId,
                success: function (result) {
                    if (result && result.code == 200) {
                        layer.alert('操作成功！', {icon: 1, title: '提示'});
                        Menu.search();
                        Menu.buildMenuTree('showTree');//列表显示菜单
                        Menu.buildMenuTree('menuTree');//选择菜单
                    }
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
        };


        var showTree, menuTree, setting = {
            data: {simpleData: {enable: true, idKey: 'menuCode', pIdKey: 'parentCode', rootPId: 0}, key: {name: 'menuName',}},
            view: {showIcon: false, selectedMulti: false}
        };

        // 渲染表格
        var tableResult = table.render({
            elem: '#' + Menu.tableId,
            url: '/menu/listPage',
            page: true,
            height: "full-158",
            cellMinWidth: 100,
            request: {pageName: 'pageNum', limitName: 'pageSize'},
            cols: Menu.initColumn()
        });

        //初始化左侧部门树
        Menu.buildMenuTree=function(treeId) {
            var zTreeObj = showTree;
            if (treeId == 'menuTree') {
                setting['callback'] = {};
                if (menuTree) menuTree.destroy();
                setting['check'] = {enable: true, chkStyle: 'radio', radioType: 'all'};
                menuTree = $.fn.zTree.init($('#' + treeId), setting, showTree.getNodes());
                return true;
            } else {
                setting['check'] = {};
                setting['callback'] = { onClick: Menu.onClickMenu };
            }
            $.ajax({
                async: false, type: 'get', url: '/menu/menuData',
                success: function (result) {
                    if (result && result.code == 200) {
                        if (zTreeObj) zTreeObj.destroy();
                        zTreeObj = $.fn.zTree.init($('#' + treeId), setting, result.data);
                        zTreeObj.expandAll(true);
                        if (treeId == 'showTree') showTree = zTreeObj;
                        else menuTree = zTreeObj;
                    } else
                        layer.alert(result.msg || '刷新树失败！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
        }

        Menu.buildMenuTree('showTree');//列表显示菜单
        Menu.buildMenuTree('menuTree');//选择菜单

        // 搜索按钮点击事件
        $('#btnSearch').click(function () {
            Menu.search();
        });

        // 添加按钮点击事件
        $('#btnAdd').click(function () {
            Menu.openAddMenu();
        });

        // 重置点击事件
        $('#resetSearch').click(function () {
            $('#queryTools input').val('');
            $('#queryTools select').val('');
            Menu.search();
        });

        // 表单验证
        form.verify({
            menuLink: function (value) {
                var menuType = $('input[name=menuType]:checked').val();
                if ('2' == menuType && !value) {
                    return '类型为动作时必须填写菜单链接';
                }
            }
        });
        // 表单提交
        form.on('submit(saveMenu)', function (data) {
            var nodes = menuTree.getCheckedNodes(true);
            if (nodes.length > 0) {
                data.field['parentCode'] = nodes[0].menuCode;
                data.field['menuTop'] = nodes[0].menuTop + 1;
                //菜单编号= 父编号+"_"+菜单编号
                data.field['menuCode'] = data.field['parentCode']+'_'+data.field['menuCode'];
            }
            var postUrl = !data.field['menuId'] ? '/menu/addNewMenu' : '/menu/editMenu';
            $.ajax({
                async: false, type: 'post', traditional: true, data: data.field, url: postUrl,
                success: function (data) {
                    if (data && data.code == 200) {
                        layer.closeAll();
                        layer.alert('操作成功！', {icon: 1, title: '提示'});
                        Menu.buildMenuTree('showTree');
                        Menu.buildMenuTree('menuTree');
                    } else
                        layer.alert(data.msg || '操作失败了！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.closeAll();
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
            return false;
        });

        // 工具条点击事件
        table.on('tool(' + Menu.tableId + ')', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'edit') {
                Menu.onEditMenu(data.menuId);
            } else if (layEvent === 'delete') {
                layer.confirm('真的删除行么', function (index) {
                    Menu.onDeleteMenu(data.menuId);
                    return false;
                });
            }
        });

	});
}();